package cn.com.wms.Base;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.NetworkInterface;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.UUID;
import java.util.regex.Pattern;


import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;



public class Tools {

	private static Properties prop;
	private static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd");

//	public static String showValue(String key) {
//		return LocaleMessage.getMessage(key);
//	}

	public static String showValue(String key) {
		try {
			ResourceBundle rb = ResourceBundle.getBundle("i18n/messages");
			String retStr = rb.getString(key);
			// 显示时替换资源文件中 中英文换行符号$$ by ccg update 20090615
			if (retStr != null) {
				retStr = retStr.replace("$$", " ");
				retStr = retStr.replace("\\r", " ");
			}
			return retStr;
		} catch (Exception e1) {

			return "";
		}
	}

	/*public static String getLocalizedMessage(String key) {
		FacesContext context = FacesContext.getCurrentInstance();
		String bundleName = "";
		bundleName = context.getApplication().getMessageBundle();
		Locale local = null;
		if (context.getExternalContext() != null) {
			HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
			if (req != null) {
				local = (Locale) req.getSession().getAttribute("localeEncoding");
			} else {
				local = Locale.CHINESE;
			}
		} else {
			local = Locale.CHINESE;
		}

		ResourceBundle rb = ResourceBundle.getBundle(bundleName, local == null ? getLocale() : local);

		String retStr = rb.getString(key);
		// // 显示时替换资源文件中 中英文换行符号$$ by ccg update 20090615
		// if (retStr != null)
		// retStr = retStr.replace("$$", "");
		return retStr;
	}*/

	public static Date StringToDate(String dateStr, String formatStr) {
		DateFormat sdf = new SimpleDateFormat(formatStr);
		Date date = null;
		try {
			date = sdf.parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

	public static Object deepCopy(Object object) {
		try {
			ByteArrayOutputStream buf = new ByteArrayOutputStream();
			ObjectOutputStream o = new ObjectOutputStream(buf);
			o.writeObject(object);
			ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buf.toByteArray()));
			return in.readObject();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String getEnvionment(String name) {
		if (prop == null) {
			prop = new Properties();
		}
		try {
			prop.load(Tools.class.getResourceAsStream("/environment.properties"));
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return prop.getProperty(name);
	}

	public static String getBandingValue(String name) {
		if (prop == null) {
			prop = new Properties();
		}
		try {
			prop.load(Tools.class.getResourceAsStream("/bandingvalue.properties"));
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return prop.getProperty(name);
	}

	public static String getURLValue(String standard, String name) {
		if (prop == null) {
			prop = new Properties();
		}
		try {
			prop.load(Tools.class.getResourceAsStream("/standardReportProperties/standard1.properties"));
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return prop.getProperty(name);
	}

	public static String getUUID() {
		String tempId1 = UUID.randomUUID().toString();
		String strId = tempId1.substring(0, 8) + tempId1.substring(9, 13) + tempId1.substring(14, 18) + tempId1.substring(19, 23) + tempId1.substring(24);
		return strId;
	}

	public static String getFormatDate(String format) {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(date);
	}

	public static String getDate() {
		return String.valueOf(System.currentTimeMillis());
	}

	public static String getFormatDate(Date date, String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		if (date == null || "".equals(date)) {
			return null;
		} else {
			return sdf.format(date);
		}
	}

	public static String getNumString(int length, int num) {
		String rtn = "";
		for (int i = 0; i < length; i++) {
			rtn += "0";
		}
		rtn += num;
		return rtn.substring(rtn.length() - length);
	}

	public static String makeClassName(String newStr) {
		return makeFirstLetterUpperCase(makeVarName(newStr));
	}

	/**
	 * makes the first Letter UpperCase in a string
	 * @param newStr
	 * @return
	 */
	public static String makeFirstLetterLowerCase(String newStr) {
		if (newStr.length() == 0)
			return newStr;

		char[] oneChar = new char[1];
		oneChar[0] = newStr.charAt(0);
		String firstChar = new String(oneChar);
		return (firstChar.toLowerCase() + newStr.substring(1));
	}

	/**
	 * makes the first Letter UpperCase in a string
	 * @param newStr
	 * @return
	 */
	public static String makeFirstLetterUpperCase(String newStr) {
		if (newStr.length() == 0)
			return newStr;

		char[] oneChar = new char[1];
		oneChar[0] = newStr.charAt(0);
		String firstChar = new String(oneChar);
		return (firstChar.toUpperCase() + newStr.substring(1));
	}

	/**
	 * strips blank/special characters from a string and makes first char after a special character upper case (excluding the very first character of the string)
	 * @param newStr
	 * @return
	 */
	public static String makeVarName(String newStr) {
		StringBuffer retstr = new StringBuffer("");
		String specialCharacters = " _/,#'%-";
		String numericCharacters = "0123456789";
		int strlen = newStr.length();
		char[] onechar = new char[1];
		boolean nextUpper = false;
		boolean firstChar = true;

		for (int i = 0; i < strlen; i++) {
			onechar[0] = newStr.charAt(i);
			String charString = new String(onechar);
			if (specialCharacters.indexOf(charString) >= 0) {
				if (charString.equals("'"))
					nextUpper = false;
				else
					nextUpper = true;
			} else {
				if (nextUpper) {
					if (!firstChar)
						retstr.append(charString.toUpperCase());
					else
						retstr.append(charString.toLowerCase());
					firstChar = false;
					nextUpper = false;
				} else {
					retstr.append(charString.toLowerCase());
					firstChar = false;
				}
			}

		}
		// if first character is numeric, insert an 'x' at the first position
		if (numericCharacters.indexOf(String.valueOf(retstr.charAt(0))) >= 0)
			retstr = retstr.insert(0, 'x');

		return retstr.toString();
	}

	public static String makeFieldName(String name) {
		name = makeFirstLetterLowerCase(name);
		String upperCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		StringBuffer retstr = new StringBuffer("");
		for (int i = 0; i < name.length(); i++) {
			if (upperCharacters.indexOf(name.charAt(i)) != -1) {
				retstr.append("_");
			}
			retstr.append(String.valueOf(name.charAt(i)).toLowerCase());
		}
		return retstr.toString();
	}

	public static void setProperty(Object bean, String keyName, String keyValue) {
		keyName = Tools.makeVarName(keyName);
		try {
			BeanUtils.setProperty(bean, keyName, keyValue);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}

	/*public static Object getBean(String name) {
		Object bean = null;
		ApplicationContext applicationContext = ContextLoaderListener.getApplicationContext();
		if (applicationContext != null) {
			bean = applicationContext.getBean(name);
		}
		return bean;
	}*/

	public static String list2String(List<String> list, String division) {
		String str = "";
		if (list == null) {
			return str;
		}
		for (int i = 0; i < list.size(); i++) {
			String s = list.get(i);
			if (i == 0) {
				str = str + s;
			} else {
				str = str + division + s;
			}
		}
		return str;
	}

	public static List string2List(String str, String division) {
		List<String> list = new ArrayList<String>();
		String[] strs = StringUtils.split(str, division);
		for (int i = 0; i < strs.length; i++) {
			list.add(strs[i]);
		}
		return list;
	}

	public static String dateToZhOrEnFormat(Date date) {
		SimpleDateFormat formatZhT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 中文带时分秒
		SimpleDateFormat formatZh = new SimpleDateFormat("yyyy-MM-dd");// 中文不带时分秒
		SimpleDateFormat formatTime = new SimpleDateFormat("HH:mm:ss");
		String dateStr = "";
		if (date != null && !"".equals(date)) {
			if ("00:00:00".equals(formatTime.format(date))) {
				dateStr = formatZh.format(date);
			} else {
				dateStr = formatZhT.format(date);
			}
		}
		return dateStr;
	}

	public static String getId() {
		return "ID_" + getFormatDate("yyyyMMddhhmmssSSS");
	}

	/**
	 * @param arry 数组对象
	 * @param bulkhead 分割符号
	 * @return
	 */
	public static String ArrayToString(String[] arry, String bulkhead) {
		StringBuffer val = new StringBuffer("");
		if (arry.length == 0) {
			return "";
		}
		for (int i = 0; i < arry.length; i++) {
			val.append(arry[i].toString());
			if (i != arry.length - 1) {
				val.append(bulkhead);
			}
		}
		return val.toString();
	}

	/**
	 * 获得年份
	 * @return
	 */
	public static String getYear() {
		java.util.Date current = new java.util.Date();
		java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
		String updateDate = sdf.format(current);
		return updateDate.substring(0, 4);
	}

	/**
	 * 根据属性名称 获取对象set方法
	 * @param cla
	 * @param attribute
	 * @return
	 */
	public static Method getSetMethodOfAttribute(Class cla, String attribute) {
		String s = attribute.substring(0, 1).toUpperCase();
		String methodName = "set" + s + attribute.substring(1, attribute.length());
		// Method method =
		// BeanUtils.findMethodWithMinimalParameters(cla,methodName);
		Method method = org.springframework.beans.BeanUtils.findMethodWithMinimalParameters(cla, methodName);
		return method;
	}

	public static int getDaysBetweenTwoDate(Date firstDate, Date secondDate) {
		int nDay = (int) ((firstDate.getTime() - secondDate.getTime()) / (24 * 60 * 60 * 1000));
		return nDay;
	}
	
	public static Date getDayStart(String dateStr) {
		try {
			Date start = SDF.parse(dateStr);
			return getDayStart(start);
		} catch (ParseException e) { 
			return null;
		}
	}
	
	public static Date getDayStart(Date date) {
		Calendar start = Calendar.getInstance();
		start.setTime(date);
		start.set(Calendar.HOUR_OF_DAY, 0);
		start.set(Calendar.MINUTE, 0);
		start.set(Calendar.SECOND, 0);
		return start.getTime();
	}
	
	public static Date getDayEnd(String dateStr) {
		try {
			Date end = SDF.parse(dateStr);
			return getDayEnd(end);
		} catch (ParseException e) { 
			return null;
		}
	}
	
	public static Date getDayEnd(Date date) {
		Calendar end = Calendar.getInstance();
		end.setTime(date);
		end.set(Calendar.HOUR_OF_DAY, 23);
		end.set(Calendar.MINUTE, 59);
		end.set(Calendar.SECOND, 59);
		return end.getTime();
	}
	//判断字符串是否为整数  
	public static boolean isInteger(String str) {    
		if(str==null || str==""){
			return false;
		}
	    Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");    
	    return pattern.matcher(str).matches();    
	}  
	//判断字符串是否为数字
	public static boolean isDecimal(String str) {    
		if(str==null || str==""){
			return false;
		}		
		Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$"); 
	    return pattern.matcher(str).matches();   
	}
	public static String getKeyFromMap(Map tempMap,String type){
		if(tempMap == null){
			return "";
		}
		Iterator<Map.Entry<String, String>> it = tempMap.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, String> entry = it.next();
			String key = entry.getKey();
			String value = entry.getValue();
			if(value.equals(type)){
			    return key;
			}
		}
		return "";
	}
	//反转MAP方便生成日志
	public static Map<String, String> reverseMap(Map<String, String> map) {
		if(map == null){
			return null;
		}
		Map<String, String> newMap = new HashMap<String,String>();
		Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, String> entry = it.next();
			String key = entry.getKey();
			String value = entry.getValue();
			newMap.put(value, key);
		}
		return newMap;
	}
    public static String getMacAddress(){  
    	try{
            Enumeration<NetworkInterface> ni = NetworkInterface.getNetworkInterfaces();           
            while(ni.hasMoreElements()){  
                NetworkInterface netI = ni.nextElement();  
                  
                byte[] bytes = netI.getHardwareAddress();  
                if(netI.isUp() && netI != null && bytes != null && bytes.length == 6){  
                    StringBuffer sb = new StringBuffer();  
                    for(byte b:bytes){  
                         //与11110000作按位与运算以便读取当前字节高4位  
                         sb.append(Integer.toHexString((b&240)>>4));  
                         //与00001111作按位与运算以便读取当前字节低4位  
                         sb.append(Integer.toHexString(b&15));  
                         sb.append("-");  
                     }  
                     sb.deleteCharAt(sb.length()-1);  
                     return sb.toString().toUpperCase();   
                }  
            }  
            return null;  		
    	}catch(Exception e){
    		 return null;  
    	}
    }


	/**
	 * 
	 * unicode 转换成 中文
	 * 
	 * @author fanhui
	 * 
	 *         2007-3-15
	 * 
	 * @param theString
	 * 
	 * @return
	 * 
	 */

	public static String decodeUnicode(String theString) {

		char aChar;

		int len = theString.length();

		StringBuffer outBuffer = new StringBuffer(len);

		for (int x = 0; x < len;) {

			aChar = theString.charAt(x++);

			if (aChar == '\\') {

				aChar = theString.charAt(x++);

				if (aChar == 'u') {

					// Read the xxxx

					int value = 0;

					for (int i = 0; i < 4; i++) {

						aChar = theString.charAt(x++);

						switch (aChar) {

						case '0':

						case '1':

						case '2':

						case '3':

						case '4':

						case '5':

						case '6':
						case '7':
						case '8':
						case '9':
							value = (value << 4) + aChar - '0';
							break;
						case 'a':
						case 'b':
						case 'c':
						case 'd':
						case 'e':
						case 'f':
							value = (value << 4) + 10 + aChar - 'a';
							break;
						case 'A':
						case 'B':
						case 'C':
						case 'D':
						case 'E':
						case 'F':
							value = (value << 4) + 10 + aChar - 'A';
							break;
						default:
							throw new IllegalArgumentException("Malformed   \\uxxxx   encoding.");
						}

					}
					outBuffer.append((char) value);
				} else {
					if (aChar == 't')
						aChar = '\t';
					else if (aChar == 'r')
						aChar = '\r';

					else if (aChar == 'n')

						aChar = '\n';

					else if (aChar == 'f')

						aChar = '\f';

					outBuffer.append(aChar);

				}

			} else

				outBuffer.append(aChar);

		}

		return outBuffer.toString();

	}
}